<?php

namespace App\Http\Controllers\Admin;


use App\Models\City;
use App\Models\Fang;
use App\Models\FangAttr;
use App\Models\FangOwners;
use App\services\Es;
use App\services\GaoDe;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class FangController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $fangName = $request->get('fang_name');
        $page = $request->get('page')?:1;
        $size =$request->get('size')?:2;
        $from =($page-1)*$size;
        //es 搜索    主要用于 接口  页数 每页数量 都由前端传递
        if (!empty($fangName)) {

            // 使用 es 首先Client实例化
            $hosts = [
                //在config  获取配置信息
                config('es.host') // Different credentials on different host
            ];

            $client = ClientBuilder::create()
                ->setHosts($hosts)
                ->build();

            $params = [
                //Es 分页
                "from"=> $from, //偏移量
                "size"=> $size, //每页页数
                'index' => 'fang',
                'body' => [
                    'query' => [
                        'match' => [
                            'fang_name' => $fangName
                        ]/*,       多条件搜索 or 关系 可能是 晚上找
                        'should' => [
                            'match' => [ 'my_other_field' => 'xyz' ]
                        ]*/
                    ],
                    //ex 高亮
                    "highlight" =>[
                        "pre_tags" => ["<span style='color: red'>"],
                        "post_tags" =>["</span>"],
                        "fields" =>[
                            'fang_name'=> new \stdClass()   //将任何内容转为对象
                        ]
                    ]
                ]
            ];
            //此时的结果为 数组
            $results = $client->search($params);


            $data=$results['hits']['hits'];




            //    $data = [];
            //foreach 循环数组    后端重构数据
            /* foreach ($results['hits']['hits'] as $val){
                 $data[]=$val['_source'];

              }*/

            //array_map  应该可以 没写出来  不知道为啥  不对外部数据 进行赋值
            /*
                      array_map(function ($val){

                          $data = [];
                           $data[]=$val['_source'];

                       },$results['hits']['hits']);
           ($data);*/

            //是否为 Es搜索
            $on = 1;

            return view('admin.fang.index', compact('data', 'on'));
        }


        //  数据库搜索
        /*

         $data= Fang::when($fangName,function ($query) use ($fangName){

              $query->where('fang_name','like',"%$fangName%");
          })->paginate($this->pathSize);

        */
        $data = Fang::paginate($this->pathSize);
        return view('admin.fang.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //业主数据  select ()  只查询对应字段
        $fangownerData = FangOwners::select('id', 'name')->get();

        //租期数据
        $fangRentTypeId = FangAttr::where('field_name', 'fang_rent_type')->value('id');
        $fangRentTypeData = FangAttr::where('pid', $fangRentTypeId)->select('id', 'name')->get();
        //租赁数据
        $fangRentClassId = FangAttr::where('field_name', 'fang_rent_class')->value('id');
        $fangRentClassData = FangAttr::where('pid', $fangRentClassId)->select('id', 'name')->get();

        //朝向
        $fangDirectionId = FangAttr::where('field_name', 'fang_direction')->value('id');
        $fangDirectionData = FangAttr::where('pid', $fangDirectionId)->select('id', 'name')->get();

        //配套设施
        $fangConfigId = FangAttr::where('field_name', 'fang_config')->value('id');
        $fangConfigData = FangAttr::where('pid', $fangConfigId)->select('id', 'name')->get();

        //城市 shou首级
        $cityData = City::where('pid', 0)->select('id', 'name')->get()->toArray();


        return view('admin.fang.add', compact('fangownerData', 'fangRentClassData', 'fangDirectionData', 'fangRentTypeData', 'fangConfigData', 'cityData'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        /* fang_province   fang_city  fang_region fang_addr*/
        $params = $request->except(['_token', 'file']);

        try {
            //将前端省市区 传入的id 拼接转为 详细地址
            $address = City::getCityById($params['fang_province']) . City::getCityById($params['fang_city']) .
                City::getCityById($params['fang_region']) . $params['fang_addr'];

            $res = GaoDe::getJLByAddress($address);
            list($params['longitude'], $params['latitude']) = $res;
            // dd($params);

            /*$params['longitude']=$res[0];
            $params['latitude']=$res[1];*/
            $res = Fang::create($params);   // 这里有问题 添加多少内容返回多少结果，如果没有添加的字段不在返回对象中

            //添加 Es 在添加后执行


            if ($res) {

                return redirect(route('admin.fang.index'));
            } else {
                return redirect(route('admin.fang.create'))->withErrors("添加失败");
            }
        } catch (\Exception $e) {

            return redirect(route('admin.fang.create'))->withErrors($e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /*
    * 本地上传 房源照片
    */
    public function localUploadFile(Request $request)
    {
        //接收图片 // 平且 上传到本地磁盘
        //此时 返回值是 文件名
        // dd($request->file());
        $file = $request->file('file')->store('', 'fang');

        //拼接返回路径
        $file = '/uploads/fang/' . $file;
        return $this->writeJson('0', ['file' => $file]);

    }

    /*
     * 添加时删除本地图片
     */
    public function delPic(Request $request)
    {


        $pic = $request->get('pic');
        $res = unlink(public_path() . $pic);
        if ($res) {

            return $this->writeJson(0, '', "删除成功");
        } else {

            return $this->writeJson(1103, '', "删除失败");
        }

    }


    /**
     * 创建房源 ES 索引
     *
     * 这可以时一个service层 方便在路由中创建并
     */
    public function createFangEsIndex()
    {
        try {
            // 手册 Connecting 下  HTTP Authenticationedit
            /* $hosts = [
                 //在config  获取配置信息
                 config('es.host')                    // Different credentials on different host
             ];
             $client = ClientBuilder::create()
                 ->setHosts($hosts)
                 ->build();*/
            $params = [
                'index' => 'czy888',
                'body' => [
                    'settings' => [
                        'number_of_shards' => 5,
                        'number_of_replicas' => 1
                    ],
                    'mappings' => [
                        '_source' => [
                            'enabled' => true
                        ],
                        'properties' => [  //属性索引

                            //如果同时 使用 拼音包  和中文搜索 需要自定义 属性 后面讲

                            'fang_name' => [
                                'type' => 'text', //text模糊搜索  keyword == int 整数
                                'analyzer' => 'ik_max_word', //中午分词规则
                                'search_analyzer' => 'ik_max_word' // 搜索使用中文分词
                            ]

                        ]
                    ]
                ]
            ];
            //调servic 进行实例化 Es 并调用方法 创建索引
            $res = (new Es())->createEsIndex($params);


            return $this->writeJson(0, $res['data'], $res['msg']);
        } catch (\Exception $e) {

            return $this->writeJson(11022, $res['data'], $e->getMessage());

        }

    }


   public function changStatus(Request $request){

        $params =$request->post();
      $res=  Fang::where('id',$params['id'])->update(['fang_status'=>$params['status']]);

      if ($res){

          return $this->writeJson(0,null,'success');
      }else{

          return $this->writeJson(111011,null,'success');
      }


   }
}
